package allen.ui.help;

import java.awt.BorderLayout;
import java.io.File;
import java.io.IOException;
import java.net.URL;

import javax.swing.JEditorPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.event.HyperlinkEvent.EventType;

import allen.log.Log;
import allen.log.LogFactory;

public class HelpPanel extends JPanel {

	private static Log log = LogFactory.getLog(HelpPanel.class);

	private static final long serialVersionUID = 1L;
	private JScrollPane jScrollPane;
	private JEditorPane jEditorPane;

	private void init(String filePath) {
		jEditorPane = new JEditorPane();
		try {
			jEditorPane.setPage("file:"
					+ (new File(filePath).getAbsolutePath()));
		} catch (Exception e) {
			log.err(e);
			throw new RuntimeException(e);
		}

		jEditorPane.setEditable(false);

		jScrollPane = new JScrollPane(jEditorPane);
		this.add(jScrollPane);
	}

	private void addListeners() {

		jEditorPane.addHyperlinkListener(new HyperlinkListener() {

			@Override
			public void hyperlinkUpdate(HyperlinkEvent e) {
				EventType type = e.getEventType();
				if (type == EventType.ACTIVATED) {
					URL url = e.getURL();
					log.info("click url = " + url);
					try {
						jEditorPane.setPage(url);
					} catch (IOException e1) {
						log.err(e1);
					}
				}
			}
		});
	}

	public HelpPanel(String filePath) {

		this.setLayout(new BorderLayout());
		init(filePath);
		addListeners();
	}

}
